// pages/profile/index.ts
Page({
  onLoad() {
    const app = getApp()
    this.setData({
      ...app.userProfile,
    })
  },
  getUserNickname(ev) {
    this.updateNickname(ev.detail.value)
  },
  async updateNickname(nickName) {
    if (!nickName) return
    const { code } = await wx.http.put('/userInfo', { nickName })
    console.log(code)
    if (code !== 10000) return wx.utils.toast('更新昵称失败')
  },
  getUserAvatar(ev) {
    this.updateAvatar(ev.detail.avatarUrl)
  },
  async updateAvatar(avatar) {
    wx.uploadFile({
      filePath: avatar,
      name: 'file',
      url: wx.http.baseURL + '/upload',
      header: {
        Authorization: 'Bearer ' + getApp().token,
      },
      formData: { type: 'avatar' },
      success: (result) => {
        const data = JSON.parse(result.data)
        if (data.code !== 1000) return

        this.setData({ avatar: data.data.url })
        const app = getApp()
        app.userProfile.avatar = data.data.url
      },
    })
  },
})
